package com.wangdao.wechatmall.service.admin;

import com.github.pagehelper.PageInfo;
import com.wangdao.wechatmall.bean.bo.admin.UserReqBO;
import com.wangdao.wechatmall.bean.pojo.User;
import com.wangdao.wechatmall.bean.pojo.UserExample;
import com.wangdao.wechatmall.bean.vo.admin.BaseDataVO;
import com.wangdao.wechatmall.bean.vo.wx.WXLoginUserInfoVO;
import com.wangdao.wechatmall.bean.vo.wx.WXLoginVO;
import com.wangdao.wechatmall.mapper.UserMapper;
import com.wangdao.wechatmall.util.MyPageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author ZhangXiao on 2021/7/8
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public long getUserNumber() {
        UserExample userExample = new UserExample();
        long total = userMapper.countByExample(userExample);
        return total;
    }

    @Override
    public BaseDataVO<User> queryUsers(UserReqBO userReqBO) {

        MyPageHelper.startPage(userReqBO);

        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();

        String username = userReqBO.getUsername();
        String mobile = userReqBO.getMobile();
        if (username != null && !"".equals(username)) {
            criteria.andUsernameLike("%" + username + "%");
        }
        if (mobile != null && !"".equals(mobile)) {
            criteria.andMobileLike("%" + mobile + "%");
        }
        //排序信息
        userExample.setOrderByClause(userReqBO.getSort() + " " + userReqBO.getOrder());

        List<User> users = userMapper.selectByExample(userExample);

        //获取分页信息
        PageInfo<User> userPageInfo = new PageInfo<>(users);
        long total = userPageInfo.getTotal();

        return BaseDataVO.ok(users, total);
    }

    @Override
    public WXLoginUserInfoVO selectUser(String username) {
        WXLoginUserInfoVO userInfo = new WXLoginUserInfoVO();
        User user = userMapper.selectUserByName(username);
        String avatar = user.getAvatar();
        String nickname = user.getNickname();
        userInfo.setAvatarUrl(avatar);
        userInfo.setNickName(nickname);
        return userInfo;
    }

    @Override
    public int selectId(String username) {
        int userId = userMapper.queryId(username);
        return userId;
    }
}
